﻿using HCQ2_BLL;
using HCQ2_Common;
using HCQ2_Common.Constant;
using HCQ2_Model;
using HCQ2_Model.APPModel;
using HCQ2_Model.DocModel.APIParam;
using HCQ2_Model.ViewModel.VR;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2UI_Helper;
using HCQ2WebAPI_Logic.BaseAPIController;
using HCQ2WebAPI_Logic.Filters;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    /// 购物车接口【老版本，已弃用，请使用Pay里面的接口】
    /// </summary>
    public class ShoppingCartAPIController: BaseAPI
    {
        /// <summary>
        /// 获取用户的购物车信息
        /// </summary>
        /// <param name="param">登录成功返回的用户ID</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel UserShoppingCart(BaseParam param)
        {
            T_User user = getUser(param.userid);
            UserShoppingCart cart = operateContext.bllSession.T_VRShoppingCart.GetUserShoppingCart(user.user_id);

            return ok(GlobalConstant.数据获取成功.ToString(), cart);
        }

        /// <summary>
        /// 获取用户的购物车信息-【返回信息文档】
        /// </summary>
        /// <returns></returns>
        public UserShoppingCart UserShoppingCartDoc()
        {
            return null;
        }

        /// <summary>
        /// 添加进购物车
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel Add(ShoppingCartEditParam param)
        {
            T_User user = getUser(param.userid);
            //判断购物车中是否已经存在
            T_VRShoppingCart cart = operateContext.bllSession.T_VRShoppingCart.FindSingle(w=>w.user_id==user.user_id && w.file_id== param.CommodityId);
            if (cart != null) {
                return error("购物车已经存在此商品",null);
            }

            //判断商品是否下架
            T_DocumentInfo fileInfo = operateContext.bllSession.T_DocumentInfo.FindSingle(w=>w.file_id== param.CommodityId);
            if (fileInfo == null) {
                return error("商品不存在",null);
            }
            if (fileInfo.file_status == 4) {
                return error("商品已经下架",null);
            }

            //判断是否回收
            if (fileInfo.if_remove == true) {
                return error("商品已经被删除",null);
            }


            T_VRShoppingCart addCart = new T_VRShoppingCart() {
                file_id = param.CommodityId,
                user_id = user.user_id,
                price = fileInfo.file_money
            };

            operateContext.bllSession.T_VRShoppingCart.Add(addCart);

            return ok("加入购物车成功",null);

        }

        /// <summary>
        /// 从购物车移除商品
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel Delete(ShoppingCartEditParam param)
        {
            T_User user = getUser(param.userid);
            operateContext.bllSession.T_VRShoppingCart.Delete(w=>w.user_id==user.user_id && w.file_id==param.CommodityId);
            return ok("移除商品成功",null);
        }

        /// <summary>
        /// 下单，生成“未付款”订单
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel PlaceAnOrder(PlaceAnOrderParam param)
        {
            T_User user = getUser(param.userid);

            StringBuilder checkValidMess = new StringBuilder();
            //1.验证购买中是否包含已经购买的
            if (checkPurchase(user,param.CommodityId,ref checkValidMess)) {
                return error(checkValidMess.ToString(), null, WebResultCode.Ok);
            }

            //2.验证选中购物车商品是否包含：是否下架、是否删除
            if (checkLowerShelfAndRemove(user,param.CommodityId,ref checkValidMess)) {
                return error(checkValidMess.ToString(), null);
            }

            //3.获取选中购物车中商品信息
            List<T_DocumentInfo> docInfoList = operateContext.bllSession.T_VRShoppingCart.ListUserShoppingCartCommodity(user.user_id,param.CommodityId);
            if (docInfoList.Count == 0) {
                return error("购物车不存在选中的商品信息", null);
            }

            //获取选中商品在购物车中的信息
            List<T_VRShoppingCart> shoppingCartList = operateContext.bllSession.T_VRShoppingCart.Select(w=>w.user_id==user.user_id && (param.CommodityId.Contains(w.file_id)));

            //4.计算选中商品总价
            decimal totalPrice = operateContext.bllSession.T_VRShoppingCart.GetSelectCommodityTotalMoney(param.CommodityId);

            //5.获取订单编号
            string orderCode = operateContext.bllSession.T_VROrder.GetOrderCode();

            //6.创建订单
            DateTime currentDate = DateTime.Now;
            T_VROrder order = new T_VROrder() {
                order_code = orderCode,
                pay_money = totalPrice,
                pay_pramoney = 0,
                status=0,
                user_id = user.user_id,
                create_time= currentDate,
                update_time= currentDate,
                handle_time= currentDate
            };

            //7.创建订单详细
            List<T_VROrderDetail> orderDetailList = new List<T_VROrderDetail>(docInfoList.Count);
            foreach (T_DocumentInfo doc in docInfoList) {
                T_VROrderDetail orderDetail = doc.MapTo<T_VROrderDetail>();
                orderDetail.order_code = orderCode;
                orderDetail.create_id = user.user_id;
                orderDetail.create_name = user.user_name;
                orderDetail.create_time = currentDate;
                //下面三个判断处理not null导致不能下单成功
                if (string.IsNullOrEmpty(orderDetail.doc_number)) {
                    orderDetail.doc_number = "";
                }
                if (string.IsNullOrEmpty(orderDetail.file_type))
                {
                    orderDetail.file_type = "";
                }
                if (string.IsNullOrEmpty(orderDetail.attach_url))
                {
                    orderDetail.attach_url = "";
                }
                orderDetailList.Add(orderDetail);
            }

            //创建订单
            UnitHelper.unitWork.Add<T_VROrder>(order);
            //创建订单详细
            UnitHelper.unitWork.BatchAdd<T_VROrderDetail>(orderDetailList.ToArray());
            //删除购物车中选中商品
            foreach (var cart in shoppingCartList) {
                UnitHelper.unitWork.Delete<T_VRShoppingCart>(cart);
            }
            UnitHelper.unitWork.Save();
            
            return ok("下单成功",null);
        }

        /// <summary>
        /// 立即购买，在购物车中直接下单购买---购买优先使用赠币
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel Purchase(PlaceAnOrderParam param)
        {
            T_User user = getUser(param.userid);

            try
            {
                StringBuilder checkValidMess = new StringBuilder();

                //1.验证购买中是否包含已经购买的
                if (checkPurchase(user, param.CommodityId, ref checkValidMess))
                    return error(checkValidMess.ToString(), null, WebResultCode.Ok);//0：表示已经购买过

                //2.验证选中购物车商品是否包含：是否下架、是否删除
                if (checkLowerShelfAndRemove(user, param.CommodityId, ref checkValidMess))
                    return error(checkValidMess.ToString(), null);

                //3.获取选中购物车中商品信息
                List<T_DocumentInfo> docInfoList = operateContext.bllSession.T_VRShoppingCart.ListUserShoppingCartCommodity(user.user_id, param.CommodityId);
                if (docInfoList.Count == 0)
                    return error("购物车不存在选中的商品信息", null);

                //选中商品中不包含购物车里面的
                if (docInfoList.Count != param.CommodityId.Length)
                    return error("购物车不存在选中的某些商品信息", null);
                    
                //4.计算选中商品总价
                decimal totalPrice = operateContext.bllSession.T_VRShoppingCart.GetSelectCommodityTotalMoney(param.CommodityId);

                //5.计算选中商品中系统管理员上传商品的总价
                decimal systemCommodityTotalPric = operateContext.bllSession.T_VRShoppingCart.GetSelectSystemCommodityTotalMoney(param.CommodityId);

                //扣减日志
                T_VROrder_Log log = new T_VROrder_Log();
                //6.验证用户金币是否充足，充足进行扣减
                if (checkUserMoney(totalPrice, systemCommodityTotalPric, ref user, ref log) == false)
                    return error("赠币和金币不够支付选购的商品", null);

                //获取选中商品在购物车中的信息
                List<T_VRShoppingCart> shoppingCartList = operateContext.bllSession.T_VRShoppingCart.Select(w => w.user_id == user.user_id && (param.CommodityId.Contains(w.file_id)));

                //7.获取订单编号
                string orderCode = operateContext.bllSession.T_VROrder.GetOrderCode();

                //8.创建订单
                DateTime currentDate = DateTime.Now;
                T_VROrder order = new T_VROrder()
                {
                    order_code = orderCode,
                    pay_money = totalPrice,
                    pay_pramoney = totalPrice,
                    status = 2,
                    user_id = user.user_id,
                    create_time = currentDate,
                    update_time = currentDate,
                    handle_time = currentDate
                };

                //9.创建订单详细
                List<T_VROrderDetail> orderDetailList = new List<T_VROrderDetail>(docInfoList.Count);
                foreach (T_DocumentInfo doc in docInfoList)
                {
                    T_VROrderDetail orderDetail = doc.MapTo<T_VROrderDetail>();
                    orderDetail.order_code = orderCode;
                    orderDetail.create_id = user.user_id;
                    orderDetail.create_name = user.user_name;
                    orderDetail.create_time = currentDate;

                    orderDetailList.Add(orderDetail);

                    doc.pay_num++;
                }

                //商品ID字符串
                string commodityIdStr = string.Join(",", param.CommodityId);
                log.create_time = currentDate;
                log.user_id = user.user_id;
                log.optype = 3;
                log.content = string.Format("使用【立即购买】订单编号：{0}，购买：{1}件商品，商品ID字符串：{2}", orderCode, param.CommodityId.Length, commodityIdStr);

                //创建订单
                UnitHelper.unitWork.Add<T_VROrder>(order);
                //创建订单详细
                UnitHelper.unitWork.BatchAdd<T_VROrderDetail>(orderDetailList.ToArray());
                //删除购物车中选中商品
                foreach (var cart in shoppingCartList)
                {
                    UnitHelper.unitWork.Delete<T_VRShoppingCart>(cart);
                }
                //更新用户金币和赠币
                UnitHelper.unitWork.Update<T_User>(user);
                //更新文件购买次数
                foreach (T_DocumentInfo doc in docInfoList)
                {
                    UnitHelper.unitWork.Update<T_DocumentInfo>(doc);
                }
                //记录扣减日志
                UnitHelper.unitWork.Add<T_VROrder_Log>(log);
                UnitHelper.unitWork.Save();

                return ok(string.Format("购买成功,订单号：{0}", orderCode), orderCode);
            }
            catch (Exception e) {
                T_VROrder_Log log = new T_VROrder_Log();
                log.content = string.Format("用户：{0}操作【立即购买】出现异常：{1}",user.user_name,e.Message);
                UnitHelper.unitWork.Add<T_VROrder_Log>(log);
                UnitHelper.unitWork.Save();
                throw e;
            }
        }

        /// <summary>
        /// 购买未付款订单--优先使用赠币
        /// </summary>
        /// <param name="OrderCode"></param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel PurchaseOrder(String OrderCode)
        {
            //购买未付款的订单


            return ok();
        }

        #region 私有
        /// <summary>
        /// 验证选中商品是否已购买
        /// </summary>
        /// <param name="user">当前用户</param>
        /// <param name="CommodityId">选中商品ID数组</param>
        /// <param name="checkValidMess">错误消息</param>
        /// <returns>如果包含已购买返回：true、否则返回false</returns>
        private bool checkPurchase(T_User user,int[] CommodityId,ref StringBuilder checkValidMess)
        {
            var UserPurchased = operateContext.bllSession.T_VRShoppingCart.ListUserPurchased(user.user_id,CommodityId);
            if (UserPurchased.Count > 0)
            {
                checkValidMess.Append("如下已购买：");
                foreach (var v in UserPurchased)
                {
                    checkValidMess.Append(v.file_name).Append(",");
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 验证选中商品是否包含删除或状态：私有:0 /(公开)，待审核:1 /（管理员修改），3：免费共享，4：下架，6：审核未通过
        /// </summary>
        /// <param name="user"></param>
        /// <param name="CommodityId"></param>
        /// <param name="checkValidMess"></param>
        /// <returns>如果包含返回：true、否则返回false</returns>
        private bool checkLowerShelfAndRemove(T_User user, int[] CommodityId, ref StringBuilder checkValidMess)
        {
            var UserLowerShelfAndRemove = operateContext.bllSession.T_VRShoppingCart.ListUserLowerShelfAndRemove(user.user_id,CommodityId);
            if (UserLowerShelfAndRemove.Count > 0)
            {
                checkValidMess.Append("如下商品未上架或删除：");
                foreach (var v in UserLowerShelfAndRemove)
                {
                    checkValidMess.Append(v.file_name).Append(",");
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 验证用户的赠币+金币是否足够支付所选商品的总价
        /// </summary>
        /// <param name="user">购买用户</param>
        /// <param name="totalPrice">选中商品总价</param>
        /// <param name="systemCommodityTotalPric">系统管理员上传商品需要支付总金额</param>
        /// <param name="log">扣减记录</param>
        /// <returns>如果足够返回：true、否则返回false</returns>
        private bool checkUserMoney(decimal totalPrice,decimal systemCommodityTotalPric,ref T_User user,ref T_VROrder_Log log)
        {
            /*
             1.赠币只能支付系统管理员上传的商品
             2.金币：20 赠币：10  需要支付：25，金币：
             */

            //需要用金币支付的金额
            decimal buyTotalPrice = totalPrice - systemCommodityTotalPric;

            //赠币足够支付系统商品
            if (user.give_gold >= systemCommodityTotalPric)
            {
                //金币足够支付
                if (user.buy_gold >= buyTotalPrice)
                {
                    //扣减赠币
                    user.give_gold = user.give_gold - systemCommodityTotalPric;
                    //扣减金币
                    user.buy_gold = user.buy_gold - buyTotalPrice;

                    //记录扣减日志
                    log.total_money = totalPrice;
                    log.subtract_buy_gold = buyTotalPrice;
                    log.subtract_give_gold = systemCommodityTotalPric;
                    log.buy_gold = user.buy_gold;
                    log.give_gold = user.give_gold;
                    return true;
                }

                return false;
            }

            //赠币不够支付系统商品，需要金币支付的金额
            decimal surplusBuyTotalPrice = systemCommodityTotalPric - user.give_gold;

            //判断金币是否足够支付
            if (user.buy_gold >= (surplusBuyTotalPrice + buyTotalPrice))
            {
                log.subtract_give_gold = user.give_gold;
                //扣减赠币
                user.give_gold = 0;
                //扣减金币
                user.buy_gold = user.buy_gold - (surplusBuyTotalPrice + buyTotalPrice);

                //记录扣减日志
                log.total_money = totalPrice;
                log.subtract_buy_gold = (surplusBuyTotalPrice + buyTotalPrice);
                log.buy_gold = user.buy_gold;
                log.give_gold = user.give_gold;
                return true;
            }
            else {
                return false;
            }    
        }

        #endregion
    }
}
